<script setup lang="ts">
import { ref, defineProps, defineEmits, withDefaults, watch, onMounted, computed } from "vue";
import { ElMessage } from "element-plus";
import { getDeviceGroupByIdApi, updateDeviceGroupApi, getDeviceGroupOptionsApi } from "@/api/products/deviceGroup";
import { useLogic } from "@/views/system/user/logic/logic";
import { buildTree } from '@/utils/helper';
import { getGroupPurposeOptions } from '@/utils/appCommon/appCommonOptions/deviceGroup'
import { useI18n } from "vue-i18n";

const {deptTreeList,getDeptTree}  = useLogic()
const { t } = useI18n();

// 设备分组选项列表
const deviceGroupOptions = ref<any[]>([]);
const treeDeviceGroupOptions = ref<any[]>([]);
const currentGroupId = ref<number>(0);
const purposeOptions = ref<Array<{ val: string; label: string }>>([])

// 获取设备分组选项
const getDeviceGroupOptions = async () => {
  try {
    const response = await getDeviceGroupOptionsApi();
    if (response.code === 0) {
      // 过滤掉当前正在编辑的分组及其子分组，防止循环引用
      const filteredOptions = response.data?.options.filter((item: any) =>
        item.id !== currentGroupId.value && !isDescendant(item.id)
      ) || [];
      deviceGroupOptions.value = filteredOptions;
      // 构建树形结构选项
      treeDeviceGroupOptions.value = buildTree(filteredOptions, 'id', 'parentId', 'children');
    }
  } catch (error) {
    console.error('Failed to get device group options:', error);
  }
};

// 判断是否是当前分组的子分组（防止循环引用）
const isDescendant = (id: number): boolean => {
  if (!currentGroupId.value || !deviceGroupOptions.value.length) return false;

  // 这里简化处理，实际应该递归检查所有层级
  return deviceGroupOptions.value.some(item => item.parentId === id);
};

onMounted(async () => {
  await getDeptTree();
  // 初始化数据
  // 获取用途选项
  purposeOptions.value = await getGroupPurposeOptions()
});

// 定义props
const props = withDefaults(defineProps<{
  visible: boolean;
  group: any;
}>(), {
  visible: false,
  group: null
});

// 本地状态管理弹窗显示
const dialogVisible = ref(props.visible);

// 同步props到本地状态
watch(() => props.visible, (newVal) => {
  dialogVisible.value = newVal;
}, { immediate: true });

// 通知父组件状态变化
watch(dialogVisible, (newVal) => {
  emit('update:visible', newVal);
});

// 定义emits
const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void;
  (e: 'close'): void;
  (e: 'success'): void;
}>();

// 表单数据
const formData = ref<{
  id: number;
  groupName: string;
  groupKey: string;
  purpose: string;
  deptId: number;
  remark: string;
  parentId: number; // 新增父分组ID字段
}>({
  id: 0,
  groupName: '',
  groupKey: '',
  purpose: '',
  deptId: 0,
  remark: '',
  parentId: 0
});

// 监听group数据变化，初始化表单
watch(
  () => props.group,
  async (newVal) => {
    console.log(newVal);
    if (newVal && newVal.id) {
      currentGroupId.value = newVal.id;
      try {
        const response = await getDeviceGroupByIdApi(newVal.id);
        if (response.code === 0) {
          formData.value = {
            id: response.data.info.id,
            groupName: response.data.info.name,
            groupKey: response.data.info.groupKey,
            purpose: response.data.info.purpose,
            deptId: response.data.info.deptId,
            remark: response.data.info.remark,
            parentId: response.data.info.parentId || 0 // 获取父分组ID
          };
          // 获取设备分组选项（排除自己和子分组）
          await getDeviceGroupOptions();
        } else {
          ElMessage.error(response.msg || t("products.deviceGroupPage.getDetailsFailed"));
        }
      } catch (error) {
        ElMessage.error(t("products.deviceGroupPage.getDetailsFailed"));
        console.error('Failed to get device group details:', error);
      }
    }
  },
  { immediate: true }
);

// 提交表单
const submitForm = async () => {
  try {
    const submitData = {
      groupKey: formData.value.groupKey,
      name: formData.value.groupName,
      purpose: formData.value.purpose,
      deptId: formData.value.deptId,
      remark: formData.value.remark,
      parentId: formData.value.parentId // 包含父分组ID
    };

    const response = await updateDeviceGroupApi(formData.value.id, submitData);
    if (response.code === 0) {
      ElMessage.success(t("products.deviceGroupPage.updateSuccess"));
      emit('update:visible', false);
      emit('success');
    } else {
      ElMessage.error(response.msg || t("products.deviceGroupPage.updateFailed"));
    }
  } catch (error) {
    ElMessage.error(t("products.deviceGroupPage.updateFailed"));
    console.error('Failed to update device group:', error);
  }
};

// 重置表单
const resetForm = () => {
  if (props.group) {
    formData.value = { ...props.group, parentId: props.group.parentId || 0 };
  }
};

// 关闭弹窗
const closeDialog = () => {
  emit('update:visible', false);
  emit('close');
};
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="t('products.deviceGroupPage.editGroup')"
    :draggable="true"
    @close="closeDialog"
    width="600px"
  >
    <el-form
      :model="formData"
      label-width="120px"
      style="max-width: 500px; margin: 0 auto;"
    >
      <el-form-item :label="t('products.deviceGroupPage.groupId')" prop="id">
        <el-input v-model="formData.id" disabled />
      </el-form-item>
      <el-form-item :label="t('products.deviceGroupPage.groupName')" prop="groupName" required>
        <el-input v-model="formData.groupName" :placeholder="t('products.deviceGroupPage.searchPlaceholder')" />
      </el-form-item>
      <el-form-item :label="t('products.deviceGroupPage.groupKey')" prop="groupKey" required>
        <el-input v-model="formData.groupKey" disabled :placeholder="t('products.deviceGroupPage.searchPlaceholder')" />
        <div style="text-align: center; font-size: 12px; color: red">{{ t('products.deviceGroupPage.groupKeyHint') }}</div>
      </el-form-item>

      <el-form-item :label="t('products.deviceGroupPage.purpose')" prop="purpose">
        <el-select v-model="formData.purpose" :placeholder="t('products.deviceGroupPage.searchPlaceholder')">
          <el-option
            v-for="item in purposeOptions"
            :key="item.val"
            :label="item.label"
            :value="item.val"
          />
        </el-select>
      </el-form-item>

      <el-form-item :label="t('products.deviceGroupPage.dept')" prop="deptId">
        <el-cascader
          v-model="formData.deptId"
          class="w-full"
          :options="deptTreeList"
          :props="{
              value: 'id',
              label: 'name',
              emitPath: false,
              checkStrictly: true
            }"
          clearable
          filterable
          :placeholder="t('products.deviceGroupPage.searchPlaceholder')"
        >
          <template #default="{ node, data }">
            <span>{{ data.name }}</span>
            <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
          </template>
        </el-cascader>
      </el-form-item>
      <el-form-item :label="t('products.deviceGroupPage.remark')" prop="remark">
        <el-input v-model="formData.remark" :placeholder="t('products.deviceGroupPage.searchPlaceholder')" type="textarea" />
      </el-form-item>

      <!-- 新增父分组选择 -->
      <el-form-item :label="t('products.deviceGroupPage.parentGroup')" prop="parentId">
        <el-cascader
          v-model="formData.parentId"
          class="w-full"
          :options="treeDeviceGroupOptions"
          :props="{
              value: 'id',
              label: 'name',
              emitPath: false,
              checkStrictly: true
            }"
          clearable
          filterable
          :placeholder="t('products.deviceGroupPage.rootGroupTip')"
        >
          <template #default="{ node, data }">
            <span>{{ data.name }}</span>
            <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
          </template>
        </el-cascader>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="resetForm">{{ t("buttons.reset") }}</el-button>
        <el-button type="primary" @click="submitForm">{{ t("buttons.submit") }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
